package com.jshop.tree;

import java.util.ArrayList;
import java.util.List;
import com.jfinal.kit.JsonKit;

public class Tree {
    private List<Node> nodes;  
 
    public Tree(List<Node> nodes){  
        this.nodes = nodes;  
    }  
      
    public String buildTree(){
    	List<TreeNode> list=new ArrayList<TreeNode>();
        for (Node node : nodes) { 
            if (node.getParentId() == null) { 
            	String name=node.getName();
            	TreeNode ctd = new TreeNode(node.getId()+"", name);
            	ctd.setChildren(build(node));
            	list.add(ctd);
            }  
        }  
        return JsonKit.toJson(list);  
    }  
    
    private List<TreeNode> build(Node node){  
        List<Node> children = getChildren(node);
        List<TreeNode> list=new ArrayList<TreeNode>();
        if (!children.isEmpty()) {  
            for (Node child : children) {
                TreeNode toptree = new TreeNode(child.getId()+"", child.getName());
                toptree.setChildren(build(child)); 
                list.add(toptree);
            }
        }
        return list;
    }  
    private List<Node> getChildren(Node node){  
        List<Node> children = new ArrayList<Node>();  
        String id = node.getId();  
        for (Node child : nodes) {  
            if (id.equals(child.getParentId())) {  
                children.add(child);  
            }  
        }  
        return children;  
    }  
}
